//引入express模块
const express=require('express')

//引入连接池模块
const pool=require('../pool.js')

//创建路由器
const router=express.Router()

//添加详情路由(接口)
//传参方式：post
//接口地址：http://127.0.0.1:1024/v1/detail/add
router.post('/add',(req,res,next)=>{
    //获取post传递的参数
    console.log(req.body)
    //执行sql命令
    pool.query('insert into cp_detailed set ?',[req.body],(err,r)=>{
        if(err){
            next(err)
            return 
        }
        console.log(r)
        res.send({code:200,msg:'添加成功'})
    })
})

//删除详情
//传参方式：delete
//接口地址:http://127.0.0.1:1024/v1/detail/scdetail
router.delete('/scdetail/:id',(req,res,next)=>{
    //获取delete的传参
    console.log(req.params)
    //执行sql命令
    pool.query('delete from cp_detailed where cp_detailed_id=?',[req.params.id],(err,r)=>{
        if(err){
            next(err)
            return
        }
        console.log(r)
        //判断是否删除
        if(r.affectedRows=0){
            res.send({code:401,msg:'删除失败'})
        }else{
            res.send({code:200,msg:'删除成功'})
        }
    })
})

//修改详情接口
//传参方式:put
//接口地址:http://127.0.0.1:1024/v1/detail/xgdetail
router.put('/xgdetail',(req,res,next)=>{
    //获取put传递的参数
    console.log(req.body)
    //执行sql命令
    pool.query('update cp_detailed set ? where cp_detailed_id=?',[req.body,req.body.cp_detailed_id],(err,r)=>{
        if(err){
            next(err)
            return
        }
        console.log(r)
        //判断是否修改成功
        if(r.affectedRows===0){
            res.send({code:401,msg:'修改失败'})
        }else{
            res.send({code:200,msg:'修改成功'})
        }
    })
})


//查询详情接口
//传参方式：get
//接口地址http://127.0.0.1:1024/v1/detail/cxdetail
router.get('/cxdetail/:cp_detailed_id',(req,res,next)=>{
    //获取get传递的参数
    console.log(req.params)
    //执行sql命令
    pool.query('select * from cp_detailed where cp_detailed_id=?',[req.params.cp_detailed_id],(err,r)=>{
        if(err){
            next(err)
            return
        }
        console.log(r)
        //判断是否查询成功
        if(r.length===0){
            res.send({code:401,msg:'查找失败'})
        }else{
            res.send({code:200,msg:'查找成功'})
        }
    })
})

//将路由器暴露出去
module.exports=router